package com.nulldev.util.net.protocols.openSDTP2.transferTest;

import com.nulldev.util.io.FileUtil;
import com.nulldev.util.java.JVMUtil;
import com.nulldev.util.net.packets.APILevel;
import com.nulldev.util.net.packets.NetInfo;
import com.nulldev.util.net.packets.NetPacket;
import com.nulldev.util.net.packets.UniversalPacket;
import com.nulldev.util.other.ByteUtils;

@APILevel(level = 6)
public class DataTransferPacket extends UniversalPacket {
	
	public DataTransferPacket() {
		super("openSDTP2: Speed Test Data", "opensdtp2.speedTestPacket", 
				ByteUtils.randomBytes(32));
	}

	public DataTransferPacket(final int dataLength) {
		super("openSDTP2: Speed Test Data", "opensdtp2.speedTestPacket", 
				ByteUtils.randomBytes(dataLength));
	}

	@Override
	public void client(byte[] data, byte[] raw, NetInfo connection) {
		if (data.length == 0) {
			JVMUtil.async_error("Speed test failed!");
			return;
		}
		final int offset = 0;
		final long readTime_ms = (connection.readTime() <= 0 ? 1 : connection.readTime());
		final float readTime_s = (readTime_ms);
		final long speed = (long) (data.length / (offset + readTime_s) * 1000);
		JVMUtil.async_println("Recieved " + FileUtil.convertToStringRepresentation(data.length) + " in " + 
				(offset + connection.readTime()) + " ms. [" + FileUtil.convertToStringRepresentation(speed) + "/s]");
	}

	@Override
	public void server(byte[] data, byte[] raw, NetInfo connection) {
		if (data.length == 0) {
			JVMUtil.async_error("Speed test failed!");
			return;
		}
		final int offset = 0;
		final long readTime_ms = (connection.readTime() <= 0 ? 1 : connection.readTime());
		final float readTime_s = (readTime_ms);
		final long speed = (long) (data.length / (offset + readTime_s) * 1000);
		JVMUtil.async_println("Sent " + FileUtil.convertToStringRepresentation(data.length) + " in " + 
				(offset + connection.readTime()) + " ms. [" + FileUtil.convertToStringRepresentation(speed) + "/s]");
		connection.reply(new DataTransferPacket(data.length));
	}

}
